package com.swan.models;

import com.swan.beans.RoleEnum;
import com.swan.beans.StatusEnum;
import com.swan.beans.UserBean;
import com.swan.exceptions.CustomerException;
import com.swan.utils.EncryptUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    /**
     * default password of the system.
     */
    private static final String DEFAULT_PASSWORD = "123456";

    public void addUser(UserBean userBean) {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select count(0) from z_account where name = ?", userBean.getName());
            if (rs.next() && rs.getInt(1) > 0) {
                throw new CustomerException("Account exists.");
            }
            rs = db.preparedStatement("select count(0) from login where login_id = ?", userBean.getName());
            if (rs.next() && rs.getInt(1) > 0) {
                throw new CustomerException("Account exists.");
            }
            db.updateWithMode("insert into z_account (name,phone,role,status) values (?,?,?,?)", Statement.RETURN_GENERATED_KEYS, userBean.getName(), userBean.getPhone(), RoleEnum.valueOf(userBean.getRole()).getRole(), StatusEnum.ENABLE.getStatus());
            int userId = db.getGeneratedKey();
            db.updateWithMode("insert into login (login_id,password,user_id) values (?,?,?)", Statement.RETURN_GENERATED_KEYS, userBean.getName(), EncryptUtil.MD5(DEFAULT_PASSWORD), userId);
//            userBean.setId(db.getGeneratedKey());
            userBean.setId(userId);
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    public UserBean getUserById(int userId) {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from z_account where id = ?", userId);
            if (rs.next()) {
                return retrieveUser(rs);
            } else {
                throw new CustomerException("User isn't exists.");
            }
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    public boolean updateStatus(int userId, StatusEnum status) {
        return DBUtil.doSomething(db ->
                db.updateWithoutGeneratedKey("update z_account set status = ? where id = ?", status.getStatus(), userId) == 1);
    }

    public boolean removeUser(int userId) {
        return DBUtil.doSomething(db -> {
            db.updateWithoutGeneratedKey("delete from login where user_id = ?", userId);
            return db.updateWithoutGeneratedKey("delete from z_account where id = ?", userId) == 1;
        });
    }

    public List<UserBean> list() {
        List<UserBean> list = new ArrayList<>();
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from z_account where status = ?", StatusEnum.ENABLE.getStatus());
            while (rs.next()) {
                list.add(retrieveUser(rs));
            }
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
        return list;
    }

    private UserBean retrieveUser(ResultSet rs) throws SQLException {
        UserBean ret = new UserBean();
        ret.setId(rs.getInt("id"));
        ret.setPhone(rs.getString("phone"));
        ret.setName(rs.getString("name"));
        ret.setRole(rs.getInt("role"));
        return ret;
    }
}
